// axios配置
import axios from 'axios'
import promise from 'es6-promise'
import apiPath from './path.js'
import Vue from 'vue'
import store from '../store'
import Cookies from "js-cookie";

promise.polyfill()
axios.defaults.withCredentials = false
axios.defaults.headers.common['Content-Type'] = 'application/json,text/plain'
axios.defaults.retry = 4
axios.defaults.retryDelay = 1000
/*************************loadingStart************************* */
var loading, num = 0

function startLoading () {
  loading = Vue.prototype.$loading({
    lock: true,
    text: '加载中……',
    background: 'rgba(0, 0, 0, 0.7)'
  })
}

function endLoading () {
  num = 0
  loading.close()
}

function signOut () {
  Cookies.remove(process.env.COOKIE_NAME + "_companyName");
  Cookies.remove(process.env.COOKIE_NAME + "_isFirstLogin");
  Cookies.remove(process.env.COOKIE_NAME + "_isShop");
  Cookies.remove(process.env.COOKIE_NAME + "_linkName");
  Cookies.remove(process.env.COOKIE_NAME + "_merchantId");
  Cookies.remove(process.env.COOKIE_NAME + "_token");
  Cookies.remove(process.env.COOKIE_NAME + "_userInfo");
  Cookies.remove(process.env.COOKIE_NAME + "_isOwnAuth");
  Cookies.remove(process.env.COOKIE_NAME + "_businessScope");

  location.reload();
}
/**************************loadingEnd************************ */

/**************************pushLoadingStart************************ */

axios.interceptors.request.use(function (config) {
  if (window.location.href.indexOf('login') == -1) {
    if (Cookies.get(process.env.COOKIE_NAME + "_token") != undefined) {
      let now = new Date();
      let time = now.getTime() + 1000 * 60 * 300;
      let token = store.state.token
      Cookies.set(process.env.COOKIE_NAME + "_token", token, { expires: new Date(time) });
    } else {
      signOut()
    }
  }
  num++
  startLoading()
  return config
})
axios.interceptors.response.use(
  response => {
    num--
    if (num <= 0) {
      let timer = setTimeout(() => {
        endLoading()
        clearTimeout(timer)
      }, 300)
    }
    if (response.config.responseType != 'arraybuffer') {
      switch (response.data.code) {
        case 200:
          break
        case 0:
          Vue.prototype.$message({
            type: 'error',
            message: response.data.msg
          })
          break
      }
    } else {
    }
    return response
  },
  error => {
    num--
    if (num <= 0) {
      let timer = setTimeout(() => {
        endLoading()
        clearTimeout(timer)
      }, 300)
    }
    if (error.response) {
      console.log(error.response.status)
      switch (error.response.status) {
        case 401:
            Vue.prototype.$confirm('登录信息失效,请重新登录', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              signOut()
            })
            .catch(() => {
              signOut()         
            });
          break
        case 404:
          break
        case 500:
          break
        case 400:
          break
      }
    }
  }
)
/**************************pushLoadingEnd************************ */

/**
 * @param {请求地址} url
 * @param {请求参数} data
 * @param {Post/Get 默认get} method
 */
const http = (url, data, method = 'GET', responseType = 'text') => {
  return new Promise((resolve, reject) => {
    let token = store.state.token
    let obj = {
      token: token,
    }
    if (method == 'GET') {
      obj = Object.assign(obj, data)
    }
    axios({
      method: method,
      url: url,
      params: obj,
      data: data,
      responseType: responseType
    }).then(function (response) {
     
      resolve(response.data)
    }).catch(function (error) {
      console.log(error)
    })
  })
}

export {
  http,
  apiPath,
  axios
}
